import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';

abstract class PushManager {
  Future<void> initialize();

  void onHandleThing();
}

class OneSignPushManager extends PushManager {
  String oneSignKey = 'bcab9823-6f59-4cf3-a96d-372664bbd864';

  @override
  Future<void> initialize() async {
    //Remove this method to stop OneSignal Debugging
    OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);

    OneSignal.shared.setAppId("$oneSignKey");
    // OneSignal.shared.init("$oneSignKey", iOSSettings: {
    //   OSiOSSettings.autoPrompt: false,
    //   OSiOSSettings.inAppLaunchUrl: false
    // });
    // OneSignal.shared
    //     .setInFocusDisplayType(OSNotificationDisplayType.notification);
// The promptForPushNotificationsWithUserResponse function will show the iOS push notification prompt. We recommend removing the following code and instead using an In-App Message to prompt for notification permission
    await OneSignal.shared
        .promptUserForPushNotificationPermission(fallbackToSettings: true);
    OneSignal.shared.consentGranted(true);
    OneSignal.shared.setRequiresUserPrivacyConsent(true);

    final state = await OneSignal.shared.getDeviceState();
    print('status:  ${state.jsonRepresentation()}');
    RProvider.myProvider.globalMap[ConfigKey.pushKey] = state.userId;
    await RProvider.myProvider.updateGlobalMap();
    final tags = await OneSignal.shared.getTags();
    print('tags:  $tags');
    onHandleThing();
  }

  @override
  void onHandleThing() {
    OneSignal.shared.setInAppMessageClickedHandler((event) {
      Config.refreshMessageCount();
      print('setInAppMessageClickedHandler : ${event.jsonRepresentation()}');
      Config.eventBus.fire(event);
    });

    OneSignal.shared.setNotificationWillShowInForegroundHandler((event) async {
      Config.refreshMessageCount();
      print(
          'setNotificationWillShowInForegroundHandler : ${event.jsonRepresentation()}');
      if (event.notification.title == "Auto Logout") {
        await Config.clearConfig();
        Routes.navigateTo(RouterGenProviders.loginPage,
            clearStack: true,
            params: {
              "toastMessage": "Auto logout due to login in other mobile phone"
            });
        return;
      } else if (event.notification.additionalData["goto"] == "logout") {
        await Config.clearConfig();
        Routes.navigateTo(RouterGenProviders.loginPage,
            clearStack: true, params: {"toastMessage": "Please login again"});
      }
    });

    OneSignal.shared.setNotificationOpenedHandler(
        (OSNotificationOpenedResult result) async {
      Config.refreshMessageCount();
      // will be called whenever a notification is opened/button pressed.
      print('setNotificationOpenedHandler : ${result.action}');
      if (result.notification.title == "Auto Logout") {
        await Config.clearConfig();
        Routes.navigateTo(RouterGenProviders.loginPage,
            clearStack: true, params: {"autoLogout": true});
        return;
      }
      if (Config.eventBus.streamController.hasListener) {
        Config.eventBus.fire(result.notification);
      } else {
        Config.notificationToBeFired = result.notification;
      }
    });

    OneSignal.shared.setPermissionObserver((OSPermissionStateChanges changes) {
      print('setPermissionObserver : ${changes.jsonRepresentation()}');

      // will be called whenever the permission changes
      // (ie. user taps Allow on the permission prompt in iOS)
    });
    OneSignal.shared
        .setSubscriptionObserver((OSSubscriptionStateChanges changes) {
      // will be called whenever the subscription changes
      //(ie. user gets registered with OneSignal and gets a user ID)
      print('setSubscriptionObserver : ${changes.jsonRepresentation()}');
    });
    OneSignal.shared.setEmailSubscriptionObserver(
        (OSEmailSubscriptionStateChanges emailChanges) {
      // will be called whenever then user's email subscription changes
      // (ie. OneSignal.setEmail(email) is called and the user gets registered
      print(
          'setEmailSubscriptionObserver : ${emailChanges.jsonRepresentation()}');
    });
  }
}
